import pymysql
from common.config import *

"""操作数据库返回的结果为字典格式"""


class Operate_mysql:
    _conn = None

    @classmethod
    def get_conn(cls, env, library_name, port):
        """
        连接数据库
        library_name：不同的数据库名字
        port：数据库端口，不传则默认读取配置文件
        """
        host_db = getconf(env, "host_db")
        user_db = getconf(env, "user_db")
        password_db = getconf(env, "password")
        if port != None:
            port_db = port
        else:
            port_db = getconf(env, "port")
        if cls._conn is None:
            cls._conn = pymysql.connect(host=host_db, port=int(port_db), user=user_db,
                                        password=password_db, autocommit=True,
                                        charset="utf8", database=library_name)
        return cls._conn

    @classmethod
    def close_conn(cls):
        """关闭数据库连接"""
        if cls._conn:
            cls._conn.close()
            cls._conn = None

    @classmethod
    def get_cursor(cls, env, library_name, port):
        """获取游标对象"""
        return cls.get_conn(env, library_name, port).cursor(pymysql.cursors.DictCursor)

    @classmethod
    def close_cursor(cls, cursor):
        """关闭游标对象"""
        if cursor:
            cursor.close()

    @classmethod
    def get_sql_info(cls, env, library_name, sql, port=None):
        """查询sql语句记录"""
        data = None
        cursor = None
        try:
            cursor = cls.get_cursor(env, library_name, port)
            cursor.execute(sql)
            data = cursor.fetchall()  # 返回多个元组，多条记录
        except Exception as e:
            """异常提醒"""
            print("get_one error:", e)
        finally:
            cls.close_cursor(cursor)
            cls.close_conn()
        return data


if __name__ == '__main__':
    Operate_mysql().get_sql_info(env="test", library_name="buorg_point",
                                 sql="select * from mb_point_detail where card_code='1242BcA7EBcE631B8c83B4156AF78823'")
